
package com.lmx.persistence.service;

import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.common.util.JavaMailUtil;
import com.lmx.common.util.SMSUtil;
//import com.lmx.repoDomain.model.*;//huibati
import com.lmx.repoDomain.tmodel.business.User;//huibati
import com.lmx.repoDomain.tmodel.Account;
import com.lmx.repoDomain.tmodel.AuthCode;
import com.lmx.repoDomain.tmodel.Edinfo;
import com.lmx.repoDomain.tmodel.Role;//huibati
import com.lmx.repoDomain.tmodel.UserPrivate;
import com.lmx.repoDomain.tmodel.UserSession;
import com.lmx.repoDomain.tmodel.Userextend;

import io.katharsis.queryParams.QueryParams;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.*;

/**
 * #{description}
 *
 * @author Administrator
 * @version 1.00
 */
@Service
@Scope("prototype")
public class RegisterService<T>{
    private Log logger = LogFactory.getLog(this.getClass());

    @PersistenceContext
    private EntityManager em;

    @Autowired
    protected GenericService dslJpaService;
    @Autowired
    private CommonService commonService;


    /**
     * 发送验证码
     * @param requestParams
     * @return
     */
    public  Iterable<AuthCode> sendAuthCode(final QueryParams requestParams){
        ArrayList<AuthCode> authCodes = new ArrayList<AuthCode>();
        //获取参数map
        Map<String , String> keyMap = CommonUtil.getKeyMapByFilter(requestParams);
        String mobile = keyMap.get("mobile");
        String mail = keyMap.get("mail");
        String type = keyMap.get("type");
        if(type == null || StringUtils.isBlank(type)) type = "reg";  //默认注册验证码
        //发送验证码
        String key = "";
        String validationNum = CommonUtil.getValidationNum() + "";
        logger.debug("注册验证码：" + validationNum +" "+mobile+" "+type);
        if(mobile != null && !"".equals(mobile)){
            key = mobile;
            sendCodeBySMS(mobile,validationNum,type);
        }
        if(mail != null && !"".equals(mail)){
            key = mail;
            sendCodeByEmail(mail,validationNum,type);
        }
        //返回token
        AuthCode authCode = new AuthCode();
        UUID uuid = UUID.randomUUID();
        authCode.setToken(uuid.toString());
        authCode.setId((long)CommonUtil.buildRandom(6));
        authCodes.add(authCode);

        ActionContextHolder.getAuthCodeHolder().put(key,validationNum);
        return authCodes;
    }

    /**
     * 发送短信验证码
     * @param mobile
     */
    public void sendCodeBySMS(String mobile,String validationNum,String type){
        SMSUtil.getInstance().sendSMS(mobile,validationNum,type);
    }

    /**
     * 发送邮箱验证码
     * @param mail
     */
    public void sendCodeByEmail(String mail,String validationNum,String type){
        String content = "";
        String regContent = "您好！ <br>" +
                "感谢您注册呼叫云！ <br><br>"
                + "请您在48小时内复制下方验证码到填写到注册页面，验证您的电子邮箱： <br>" +
                validationNum + "<br>" +
//                "如果邮箱未验证，您将无法正常使用一些呼叫云功能，请您及时验证邮箱。 <br>" +
                "<br>" +
                "您在使用呼叫云产品的过程中遇到任何问题，请及时联系我们。 <br>" +
                "<br>" +
                "支持邮箱： callcloud@callcloud.cn <br>" +
                "联系电话：＋ 010 57990757<br>" +
                "<br>" +
                "感谢您对呼叫云的信任与支持！ <br>" +
                "<br>" +
                "呼叫云";
        String resetContent = " 验证码 " + validationNum + " ，您正在尝试修改呼叫云登录密码，请妥善保管账户信息。 ";
        if("reg".equals(type)) content = regContent;
        if("reset".equals(type)) content = resetContent;

                //邮件主题  邮件内容  收件人
        JavaMailUtil.getInstance().doSendHtmlEmail("验证码", content, mail);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    public UserSession register(UserSession user){
        logger.debug("开始注册方法");
        String key = "";
        if(!StringUtils.isBlank(user.getStaffMail())  && "2".equals(user.getRegWay())){ //企业注册
            key = user.getStaffMail();
            user.setRole(commonService.getEntRole());
        }else  if(!StringUtils.isBlank(user.getStaffTel())  && "1".equals(user.getRegWay())){ //客服注册
            key = user.getStaffTel();
            user.setRole(commonService.getCSRole());
        }else {
            logger.debug("注册参数错误，注册失败");
            user.setErrcode(ICommonConstants.INTERFACEERRO.OTHERFAIL.ordinal());
            return user;
        }
        String authCode = ActionContextHolder.getAuthCodeHolder().get(key);
        if(StringUtils.isBlank(authCode) || !authCode.equals(user.getAuthCode())){
            logger.debug("注册验证码错误");
            user.setErrcode(ICommonConstants.REGFAILCAUSE.AUTHCODEFAIL.ordinal());//验证码验证失败
            return user;
        }

        //判断注册用户是否重复
        String queryStr = "SELECT u FROM UserPrivate u WHERE u.loginName = ?1";
        List userList = this.em.createQuery(queryStr)
                .setParameter(1,key)
                .getResultList();
        if(userList.size() > 0){
            logger.debug("注册：该用户已存在");
            user.setErrcode(ICommonConstants.REGFAILCAUSE.ALREADYEXIST.ordinal());//该用户已存在
            return user;
        }

   /*     if (user.getLoginName() == null){
            logger.debug("设置登录名为注册手机或邮箱");
            user.setLoginName(key);
        }*/
        user.setLoginName(key);
        user.setName(key);

        //创建user
        Userextend userextend = new Userextend();
        dslJpaService.setEntityClass(Userextend.class);
        userextend = (Userextend)dslJpaService.create(userextend);

        Edinfo edinfo = new Edinfo();
        dslJpaService.setEntityClass(Edinfo.class);
        edinfo = (Edinfo)dslJpaService.create(edinfo);

/*        UserAgent userAgent = new UserAgent();
        dslJpaService.setEntityClass(UserAgent.class);
        userAgent = (UserAgent)dslJpaService.create(userAgent);*/

        int createTime = (int)(System.currentTimeMillis()/1000);
//        user.setExtendInfo(userextend);
//        user.setEdinfo(edinfo);
        user.setStatus((short)ICommonConstants.IDCERTIFICATION.NOTAPPLYCERTIFY.ordinal());
//        user.setAgentinfo(userAgent);
        if(user.getInviter() != null){
            UserPrivate userPrivate = this.em.find(UserPrivate.class,Long.parseLong(user.getInviter()));
//            user.setInviteUser(userPrivate);
            logger.debug("reg Inviter ::: " + user.getInviter());
        }

        dslJpaService.setEntityClass(UserPrivate.class);
        UserPrivate userOnly = new UserPrivate();
        BeanUtils.copyProperties(user,userOnly);
        userOnly = (UserPrivate)dslJpaService.create(userOnly);
        BeanUtils.copyProperties(userOnly,user);

        //创建Account表
        Account account = new Account();
        User accountUser = this.em.find(User.class,userOnly.getId());
        account.setUser(accountUser);
        account.setBalance(0.0);
//        account.setStatus();//账户表状态
        dslJpaService.setEntityClass(Account.class);
        dslJpaService.create(account);

        logger.debug("注册成功");
        return user;
    }

    /**
     * 用户重置密码
     * @param userSession
     * @return
     */
    public UserSession resetPassword(UserSession userSession){
        logger.debug("重置密码方法开始");
        String key = userSession.getStaffTel();
        if(!StringUtils.isBlank(userSession.getStaffMail())  && "2".equals(userSession.getRegWay())) key = userSession.getStaffMail();
        String authCode = ActionContextHolder.getAuthCodeHolder().get(key);
        if(StringUtils.isBlank(authCode) || !authCode.equals(userSession.getAuthCode())){
            logger.debug("重置密码：验证码错误");
            userSession.setErrcode(ICommonConstants.RESETFAILCAUSE.AUTHCODEFAIL.ordinal());//验证码验证失败
            return userSession;
        }
/*
        String queryStr = "SELECT u FROM UserPrivate u WHERE u.phone = '" + key + "'";
        if(!StringUtils.isBlank(userSession.getEmail())  && "2".equals(userSession.getRegWay())){
            queryStr = "SELECT u FROM UserPrivate u WHERE u.email =  '" + key + "'";
        }
        Query q = this.em.createQuery(queryStr);
        List list = q.getResultList();
*/

        List list = this.em.createQuery("SELECT u FROM UserPrivate u WHERE u.loginName = ?1")
                .setParameter(1,key)
                .getResultList();
        if(list.size() == 0){
            logger.debug("重置密码：不存在此用户");
            userSession.setErrcode(ICommonConstants.RESETFAILCAUSE.NOTEXIST.ordinal());//验证码验证失败
            return userSession;
        }
        UserPrivate user = (UserPrivate)list.get(0);
        user.setPassword(userSession.getNewPassword());
        dslJpaService.setEntityClass(UserPrivate.class);
        user = (UserPrivate)dslJpaService.update(user);
//        BeanUtils.copyProperties(user,userSession);
        userSession.setPassword(null);
        logger.debug("重置密码成功");
        return userSession;
    }

    /**
     * 用户修改密码
     * @param userSession
     * @return
     */
    public UserSession modifyPassword(UserSession userSession){
        logger.debug("开始修改密码。");
        dslJpaService.setEntityClass(UserPrivate.class);
        UserPrivate userPrivate = (UserPrivate)dslJpaService.findOne(userSession.getId());
        if(StringUtils.isBlank(userSession.getPassword()) || !userSession.getPassword().equals(userPrivate.getPassword())){
            logger.debug("修改密码:旧密码错误");
            userSession.setErrcode(ICommonConstants.MODIFYPASSWORDCAUSE.OLDPASSWORDERRO.ordinal());
            return userSession;

        }
        userPrivate.setPassword(userSession.getNewPassword());
        dslJpaService.update(userPrivate);
        userSession.setPassword(null);
        logger.debug("修改密码成功");
        return userSession;
    }



}
